<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\GoodsModel;
use support\Cache;
use support\Request;
use support\Response;
use plugin\admin\app\model\GoodsSpec;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 商品规格 
 */
class GoodsSpecController extends Crud
{
    
    /**
     * @var GoodsSpec
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new GoodsSpec;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('goods-spec/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $data = $this->insertInput($request);
            $data['is_temp'] = 1;
            $id = $this->doInsert($data);

            $goodsSpec = GoodsSpec::where('id', $id)->first()->toArray();

            $specs = GoodsSpec::where('model_id', $goodsSpec['model_id'])->orderBy('sort')->get()->toArray();

            Cache::set('model-' . $goodsSpec['model_id'], $specs);

            return $this->json(0, 'ok', ['id' => $id]);
        }
        return view('goods-spec/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $goodsSpec = GoodsSpec::where('id', $request->post('id'))->first()->toArray();

            $specs = Cache::get('model-' . $goodsSpec['model_id']);

            foreach ($specs as $key=>$spec) {
                if ($spec['id'] == $goodsSpec['id']) {
                    $spec['values'] = $request->post('values');
                    $spec['name'] = $request->post('name');
                    $specs[$key] = $spec;
                }
            }

            Cache::set('model-' . $goodsSpec['model_id'], $specs);
            return $this->json(0, 'ok');
        }
        return view('goods-spec/update');
    }

    public function sku(Request $request): Response
    {
        $modelId = $request->post('model_id');

        $specs = Cache::get('model-' . $modelId);

//        $specs = GoodsSpec::where('model_id', $modelId)->orderBy('sort')->get()->toArray();

        $header = [];
        $arrs = [];
        foreach ($specs as $spec) {
            $header[] = $spec['name'];
            $arrs[] = explode(',', $spec['values']);
        }

        $header[] = '库存';
        $header[] = '价格';
        $header[] = '图片';

        $html = '<table class="layui-table">';

        $html .= '<tr>';
        foreach ($header as $value) {
            $html .= '<td>' . $value . '</td>';
        }

        $html .= '</tr>';

        $skus = cartesian_product($arrs);

        foreach ($skus as $key=>$sku) {
            $html .= '<tr>';

            $skuStr = urlencode(json_encode($sku, JSON_UNESCAPED_UNICODE));
            foreach ($sku as $value) {
                $html .= <<< CONTENT
                <td>{$value}</td>
CONTENT;
            }

            $html .= '<td><input type="hidden" name="skuspec[]" value="' . $skuStr . '" /><input type="text" name="skucount[]" value="0" class="layui-input"></td><td><input type="text" name="skuprice[]" value="0" class="layui-input"></td><td><img src="" width="100" /><input type="text" style="display:none" name="skuthumb[]" value="" />
                            <button type="button" class="pear-btn pear-btn-primary pear-btn-sm image" id="image'. $key .'" permission="app.admin.upload.avatar">
                                <i class="layui-icon layui-icon-upload"></i>上传图片
                            </button></td>';

            $html .= '</tr>';
        }

        $html .= '</table>';

        return json(['code' => 0, 'msg' => 'ok', 'data' => $html]);
    }

    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);
//        $this->doDelete($ids);

        $id = $ids[0];
        $goodsSpec = GoodsSpec::where('id', $id)->first()->toArray();

        $specs = Cache::get('model-' . $goodsSpec['model_id']);

        foreach ($specs as $key=>$spec) {
            if (in_array($spec['id'], $ids)) {
                unset($specs[$key]);
            }
        }

        Cache::set('model-' . $goodsSpec['model_id'], $specs);

        return $this->json(0);
    }

    protected function formatNormal($items, $total): Response
    {
        $models = GoodsModel::list();
        $models = array_combine(
            array_column($models, 'value'),
            array_values($models)
        );

        foreach ($items as $key=>$item) {
            $items[$key]['model_text'] = $models[$item['model_id']]['name'];
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }

}
